<template>
  <div>
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item prop="auditStatus">
        <el-select
          v-model="dataForm.auditStatus"
          placeholder="业务状态"
          clearable
        >
          <el-option
            v-for="i in auditStatusList"
            :key="i.id"
            :value="i.id"
            :label="i.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="worksheetType">
        <el-cascader
          expand-trigger="hover"
          :options="options"
          v-model="selectedOptions"
          placeholder="业务类型"
          @change="changeWorksheetType"
          clearable
        >
        </el-cascader>
      </el-form-item>
      <el-form-item prop="repairmanId">
        <el-select
          v-model="dataForm.repairmanId"
          placeholder="维修人员"
          clearable
        >
          <el-option
            v-for="item in repairList"
            :key="item.userId"
            :label="item.name"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="startTime">
        <el-date-picker
          v-model="dataForm.startTime"
          type="datetime"
          value-format="timestamp"
          placeholder="开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="endTime">
        <el-date-picker
          v-model="dataForm.endTime"
          type="datetime"
          value-format="timestamp"
          placeholder="完成时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button
          v-if="isAuth('feature:work:add')"
          type="primary"
          @click="addOrUpdateHandle"
          >新增
        </el-button>
        <el-button
          v-if="isAuth('feature:repair:delete')"
          type="danger"
          :disabled="dataListSelections.length <= 0"
          @click="deleteHandle()"
          >批量拒绝
        </el-button>
        <el-button type="info" @click="dataForm = {}">重置</el-button>
        <el-button type="info" @click="refresh">刷新</el-button>
        <el-button type="success" @click="exportExcel">导出业务记录</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
        :selectable="selectable"
      >
      </el-table-column>
      <el-table-column
        width="150"
        fixed="left"
        prop="applicantName"
        label="申请者"
      >
      </el-table-column>
      <el-table-column width="150" prop="auditorName" label="审批者">
      </el-table-column>
      <el-table-column width="150" prop="worksheetType" label="业务类型">
        <template slot-scope="scope">
          {{
            typeArr.find((res) => res.id === scope.row.worksheetType)
              ? typeArr.find((res) => res.id === scope.row.worksheetType).name
              : ''
          }}
        </template>
      </el-table-column>
      <el-table-column width="150" prop="adminNote" label="管理员备注">
      </el-table-column>
      <el-table-column width="150" prop="memo" label="备注信息">
      </el-table-column>
      <el-table-column width="150" prop="auditStatus" label="业务状态">
        <template slot-scope="scope">
          <span v-if="scope.row.auditStatus === 0">
            <el-tag>等待审核</el-tag>
          </span>
          <span v-else-if="scope.row.auditStatus === 1">
            <el-tag type="success">审批完成</el-tag>
          </span>
          <span v-else-if="scope.row.auditStatus === 2">
            <el-tag type="info">处理完成</el-tag>
          </span>
          <span v-else-if="scope.row.auditStatus === 3">
            <el-tag type="warning">等待处理</el-tag>
          </span>
          <span v-else-if="scope.row.auditStatus === -1">
            <el-tag type="error">审核失败</el-tag>
          </span>
          <span v-else>
            <el-tag>未知错误</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="150" prop="repairmanName" label="维修人员">
        <template slot-scope="scope">
          {{ scope.row.repairmanId !== null ? scope.row.repairmanName : '无' }}
        </template>
      </el-table-column>
      <el-table-column width="150" prop="applyTime" label="申请时间">
      </el-table-column>
      <el-table-column width="150" prop="startTime" label="开始时间">
      </el-table-column>
      <el-table-column width="150" prop="endTime" label="结束时间">
      </el-table-column>
      <el-table-column fixed="right" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="warning"
            :disabled="scope.row.auditStatus !== 0"
            @click="deleteHandle(scope.row.id)"
            >拒绝
          </el-button>
          <el-button
            v-if="userInfo.type === 1"
            size="small"
            type="success"
            @click="handleNode(scope.row.id)"
            >备注
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="size"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <el-dialog
      @closed="onClosed"
      v-loading="globalLoading"
      title="新增业务"
      width="800px"
      :visible.sync="addVisible"
    >
      <el-form
        :rules="formRules"
        label-position="left"
        label-width="80px"
        ref="formRef"
        :model="addForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人" prop="applicantId">
              <el-select v-model="addForm.applicantId">
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.name"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="worksheetType">
              <el-popover
                ref="menuListPopover"
                placement="bottom-start"
                trigger="click"
              >
                <el-tree
                  :data="typeTreeList"
                  :props="{
                    label: 'label',
                    children: 'children'
                  }"
                  node-key="value"
                  ref="menuListTree"
                  @current-change="menuListTreeCurrentChangeHandle"
                  :default-expand-all="true"
                  :highlight-current="true"
                  :expand-on-click-node="false"
                >
                </el-tree>
              </el-popover>
              <el-input
                v-model="addForm.worksheetTypeName"
                v-popover:menuListPopover
                :readonly="true"
                placeholder="点击选择业务类型"
                class="menu-list__input"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="附件" prop="worksheetTypeName">
              <div style="display: flex">
                <el-upload
                  ref="upload"
                  action=""
                  :on-change="onUploadChange"
                  :auto-upload="false"
                  :file-list="fileList"
                  :show-file-list="false"
                >
                  <el-button>上传</el-button>
                </el-upload>
                <div
                  v-if="fileList[0]"
                  style="display: flex; align-items: center; margin-left: 20px"
                >
                  <div>{{ fileList[0].name }}</div>
                  <div
                    @click="handleRemove"
                    style="margin-left: 10px; cursor: pointer"
                  >
                    <i class="el-icon-delete"></i>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修人" prop="repairmanId">
              <el-select v-model="addForm.repairmanId">
                <el-option
                  v-for="item in repairmanList"
                  :key="item.userId"
                  :label="item.name"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="备注" prop="adminNote">
              <el-input v-model="addForm.adminNote"> </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="故障地点" prop="repairEntity.faultLocation">
              <el-input v-model="addForm.repairEntity.faultLocation">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="问题描述" prop="repairEntity.problemDesc">
              <el-input v-model="addForm.repairEntity.problemDesc"> </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系方式" prop="repairEntity.contactWay">
              <el-input v-model="addForm.repairEntity.contactWay"> </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="display: flex; justify-content: flex-end">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="noteVisible" title="设置备注">
      <el-input
        type="textarea"
        v-model="adminNote"
        placeholder="备注信息"
      ></el-input>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="addAdminNode">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      globalLoading: false,
      dataListSelections: [],
      dataList: [],
      selectedOptions: [],
      // 工单类型
      options: [
        {
          value: 1,
          label: '资源申请',
          children: [
            {
              value: 2,
              label: 'VPN申请(本校师生)'
            },
            {
              value: 12,
              label: 'VPN申请(实践基地教师)'
            },
            {
              value: 3,
              label: '入网账号和电子邮箱申请'
            },
            {
              value: 10,
              label: '服务器资源申请'
            },
            {
              value: 11,
              label: '网络域名与网站开通审批'
            }
          ]
        },
        {
          value: 5,
          label: '维修申请',
          children: [
            {
              value: 6,
              label: '网络故障'
            },
            {
              value: 7,
              label: '软件故障'
            },
            {
              value: 8,
              label: '硬件故障'
            }
          ]
        }
      ],
      // 工单类型数组
      typeArr: [
        {
          id: 2,
          name: 'VPN申请(本校师生)'
        },
        {
          id: 12,
          name: 'VPN申请(实践基地教师)'
        },
        {
          id: 3,
          name: '入网账号和电子邮箱申请'
        },
        {
          id: 10,
          name: '服务器资源申请'
        },
        {
          id: 11,
          name: '网络域名与网站开通审批'
        },
        {
          id: 6,
          name: '网络故障'
        },
        {
          id: 7,
          name: '软件故障'
        },
        {
          id: 8,
          name: '硬件故障'
        }
      ],
      dataForm: {
        auditStatus: '',
        worksheetType: '',
        repairmanId: '',
        startTime: '',
        endTime: ''
      },
      repairList: [],
      auditStatusList: [
        {
          id: 0,
          name: '等待处理'
        },
        {
          id: 1,
          name: '审批完成'
        },
        {
          id: 2,
          name: '处理完成'
        },
        {
          id: 3,
          name: '等待维修'
        },
        {
          id: 4,
          name: '维修业务结束'
        },
        {
          id: -1,
          name: '审核失败'
        },

        {
          id: -2,
          name: '维修处理异常'
        }
      ],
      dataListLoading: false,
      addOrUpdateVisible: false,
      // 分页
      page: 1,
      size: 10,
      total: 0,
      addVisible: false,
      userList: [],
      typeTreeList: [],
      addForm: {
        repairEntity: {}
      },
      fileList: [],
      repairmanList: [],
      filePath: '',
      formRules: {
        applicantId: [
          {
            required: true,
            message: '请选择申请人'
          }
        ],
        worksheetType: [
          {
            required: true,
            message: '请选择业务类型'
          }
        ],
        repairmanId: [
          {
            required: true,
            message: '请选择维修人'
          }
        ],
        'repairEntity.faultLocation': [
          {
            required: true,
            message: '请输入故障地点'
          }
        ],
        'repairEntity.problemDesc': [
          {
            required: true,
            message: '请输入问题描述'
          }
        ],
        'repairEntity.contactWay': [
          {
            required: true,
            message: '请输入联系方式'
          }
        ]
      },
      adminNote: '',
      noteVisible: false,
      currentId: ''
    }
  },
  methods: {
    handleNode(id) {
      this.noteVisible = true
      this.currentId = id
    },
    addAdminNode() {
      this.$http({
        url: this.$http.adornUrl('/sys/worksheetRecord/commentWorksheet'),
        method: 'put',
        params: {
          id: this.currentId,
          note: this.adminNote
        }
      }).then(({ data }) => {
        if (data.code === 0) {
          this.adminNote = ''
          this.$message.success(data.msg)
          this.getDataList()
          this.noteVisible = false
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    async uploadFile(file) {
      const formData = new FormData()
      formData.append('file', file)
      const res = await this.$http({
        url: this.$http.adornUrl('/sys/file/addFile'),
        method: 'post',
        data: formData,
        'content-type': 'multipart/form-data'
      })
      return (
        // 'http://47.109.153.71:8080/sys/file/getFile?filename=' + res.data.url
        'https://networker.nsmc.edu.cn/sys/file/getFile?filename=' + res.data.url
      )
    },
    onUploadChange(file) {
      this.fileList = [file]
      this.filePath = ''
    },
    handleRemove() {
      this.$refs.upload.clearFiles()
      this.fileList = []
    },
    onClosed() {
      this.filePath = ''
      this.$refs.formRef.resetFields()
      this.handleRemove()
    },
    async onSubmit() {
      const { username, userId, departmentId, personalNumber } = this.userInfo
      const params = {
        ...this.addForm,
        auditorId: userId,
        repairEntity: {
          ...this.addForm.repairEntity,
          ...{
            userName: username,
            userId,
            departmentId,
            userNo: personalNumber
          }
        }
      }

      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          this.globalLoading = true
          if (this.fileList[0] && !this.filePath) {
            this.filePath = await this.uploadFile(this.fileList[0].raw)
          }
          this.$http({
            url: this.$http.adornUrl('/sys/worksheetRecord/addRecordByAdmin'),
            method: 'post',
            data: {
              ...params,
              filePath: this.filePath
            }
          })
            .then(({ data }) => {
              if (data.code === 0) {
                this.$message.success('新增成功')
                this.getDataList()
                this.addVisible = false
              } else {
                this.$message.error(data.msg)
              }
            })
            .finally(() => {
              this.globalLoading = false
            })
        }
      })
    },
    addOrUpdateHandle() {
      this.getUsersList()
      this.getTypeTree()
      this.getRepairmanList()
      this.addVisible = true
    },
    menuListTreeCurrentChangeHandle(data) {
      this.addForm = {
        ...this.addForm,
        worksheetType: data.value,
        worksheetTypeName: data.label
      }
    },
    getUsersList() {
      this.$http({
        url: this.$http.adornUrl('/sys/user/nameList'),
        method: 'get'
      }).then(({ data }) => {
        this.userList = data.data
      })
    },
    getRepairmanList() {
      this.$http({
        url: this.$http.adornUrl('/sys/repairman/getSelectList'),
        method: 'get'
      }).then(({ data }) => {
        this.repairmanList = data.data
      })
    },
    getTypeTree() {
      this.$http({
        url: this.$http.adornUrl('/sys/worksheet/type/tree'),
        method: 'get'
      }).then(({ data }) => {
        console.log(data)
        this.typeTreeList = data.data
      })
    },
    getDataList() {
      this.$http({
        url: this.$http.adornUrl('/sys/worksheetRecord/getList'),
        method: 'post',
        data: this.$http.adornData({
          ...this.dataForm
        }),
        params: {
          page: this.page,
          size: this.size
        }
      }).then(({ data }) => {
        this.dataList = data.data.list
        this.total = data.data.total
      })
    },
    changeWorksheetType(res) {
      this.dataForm.worksheetType = res[res.length - 1]
    },
    // 每页数
    sizeChangeHandle(val) {
      this.size = val
      this.page = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.page = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 获取维修人员列表
    getRepairList() {
      this.$http({
        url: this.$http.adornUrl('sys/visitor/getVisitorList'),
        method: 'post',
        data: this.$http.adornData({
          type: 5,
          page: 1,
          size: 1000000
        })
      }).then(({ data }) => {
        this.repairList = data.data
      })
    },
    // 刷新
    refresh() {
      // this.dataForm = {}
      this.getDataList()
    },
    exportExcel() {
      this.$http({
        url: this.$http.adornUrl('sys/worksheetRecord/export'),
        method: 'post',
        data: this.dataForm,
        responseType: 'blob'
      }).then(({ data }) => {
        const link = document.createElement('a')
        let blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', '业务记录列表.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
    },
    selectable(row, index) {
      return row.auditStatus === 0
    },
    // 拒绝工单
    deleteHandle(id) {
      let ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id
          })
      this.$confirm(
        `确定对[id=${ids.join(',')}]进行[${id ? '拒绝' : '批量拒绝'}]操作?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          console.log(ids)
          this.$prompt('请输入拒绝原因', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(({ value }) => {
            this.$http({
              url: this.$http.adornUrl('sys/worksheetRecord/auditWorksheet'),
              method: 'put',
              params: {
                auditType: -1,
                cause: value
              },
              data: {
                ids: [...ids]
              }
            }).then(({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.getDataList()
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          })
        })
        .catch(() => {})
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo
    }
  },
  created() {
    this.getDataList()
    this.getRepairList()
  }
}
</script>

<style></style>
